package com.yuanda.erp9.syn.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanda.erp9.syn.config.ThreadPoolManager;
import com.yuanda.erp9.syn.contant.DatabaseOperationType;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.service.erp9.ESService;
import com.yuanda.erp9.syn.service.erp9.GoodsService;
import com.yuanda.erp9.syn.util.RateCalculateUtil;
import com.yuanda.erp9.syn.vo.PluginVo;
import com.yuanda.erp9.syn.vo.RateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author zengqinglong
 * @desc 异步线程方法
 * @Date 2023/1/6 9:22
 **/
@Slf4j
@EnableAsync
@Component
public class AsyncRateHelper {
    @Resource
    private GoodsService goodsService;

    @Resource
    private ESService esService;

    /**
     * 处理plugin
     *
     * @param pluginVo
     */
    @Async
    public void handlePlugin(PluginVo pluginVo) {
        //汇率
        String rate = null;
        //关税率
        Integer tariffsRate = 0;
        //商检费
        BigDecimal inspectionChargesFee = BigDecimal.ZERO;

        if (pluginVo.getOperate().equals(DatabaseOperationType.INSERT) || pluginVo.getOperate().equals(DatabaseOperationType.UPDATE)) {
            rate = RateCalculateUtil.getUpdateOrInset(pluginVo);
            JSONObject jsonObject = JSON.parseObject(rate);
            if (jsonObject != null && !jsonObject.isEmpty()) {
                // 关税率
                tariffsRate = Double.valueOf(jsonObject.getString(RateCalculateConstants.TARIFFRATE_FIELD)).intValue();
                // 商检费
                inspectionChargesFee = new BigDecimal(jsonObject.getString(RateCalculateConstants.CIQPRICE_FIELD));
            }
        } else {
            rate = RateCalculateUtil.getDel();
        }
        //更新mysql数据库内容
        Integer integer = goodsService.updateRateByManufacturerAndModel(pluginVo, rate, tariffsRate, inspectionChargesFee);
        //更新es数据
        if (integer > 0) {
            List<CmsGoodsEntity> list = goodsService.findByManufacturerAndModel(pluginVo);
            esService.updateESData(list);
        }

    }

    /**
     * 处理rate
     *
     * @param rateVo
     */
    @Async
    public void handleRate(RateVo rateVo) {
        //更新mysql数据库内容
        //筛查操作类，新增和删除不做任何操作
        if (rateVo.getOperate().equals(DatabaseOperationType.UPDATE)) {
            //判断更新的是否是固定的一条数据是就需要全部更新
            if (checkRateVo(rateVo)) {
                log.info("更改数据为固定数据,需要全部更新汇率");
                RateCalculateUtil.updateRate(rateVo.getValue());
                Integer integer = goodsService.updateAllRate(rateVo.getValue().setScale(7, BigDecimal.ROUND_HALF_UP).toPlainString());
                // 更新es数据
                if (integer > 0) {
                    updateAllEs();
                }

            }
        }
    }

    /**
     * 更新所有es数据
     */
    public void updateAllEs() {
        ThreadPoolExecutor threadPoolExecutor = ThreadPoolManager.getInstance();
        Integer allCount = goodsService.findAllCount();
        TreeMap<Integer, Integer> pageMap = getPageMap(allCount, 20000);
        for (Integer key : pageMap.keySet()) {
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        List<CmsGoodsEntity> list = goodsService.findByLimit(key, pageMap.get(key));
                        esService.updateESData(list);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 检验是否是更新的固定汇率
     *
     * @param rateVo
     * @return
     */
    private boolean checkRateVo(RateVo rateVo) {
        if (rateVo.getType().equals("Customs") &&
                rateVo.getDistrict() == 1 &&
                rateVo.getFrom() == 2 &&
                rateVo.getTo() == 1) {
            return true;
        }
        return false;
    }

    /**
     * 分段获取数据
     *
     * @param total
     * @param pageSize
     * @return
     */
    public static TreeMap<Integer, Integer> getPageMap(Integer total, Integer pageSize) {
        TreeMap<Integer, Integer> map = new TreeMap();
        Integer num = total / pageSize;
        Integer yushu = total % pageSize;
        for (int i = 1; i <= num; i++) {
            map.put((i - 1) * pageSize + 1, pageSize);
        }
        if (yushu != 0) {
            map.put(num * pageSize + 1, pageSize);
        }
        return map;
    }
}
